<template>
  <div class="home-container">
    <h2>新闻分析系统概览</h2>

    <!-- 时间模拟控制区域 -->
    <div class="time-control">
      <el-card shadow="hover" class="time-card">
        <template #header>
          <div class="time-header">
            <el-icon><Clock /></el-icon>
            <span>时间模拟控制</span>
          </div>
        </template>
        <div class="time-content">
          <div class="time-display">
            <span>当前模拟时间：</span>
            <el-tag type="info" size="large">{{ formattedTime }}</el-tag>
          </div>
          <div class="time-config">
            <div class="time-item">
              <span class="label">初始时间：</span>
              <el-date-picker
                  v-model="initialTime"
                  :show-now="false"
                  type="datetime"
                  placeholder="选择初始时间"
                  size="small"
                  style="width: 200px"
                  :disabled="isSimulating"
              />
            </div>
            <div class="time-item">
              <span class="label">时间流速：</span>
              <el-select
                  v-model="timeSpeed"
                  placeholder="选择时间流速"
                  size="small"
                  style="width: 150px"
                  value-key="speed_description"
              >
              <el-option
                  v-for="tsa in timeSpeedArray"
                  :key="tsa.speed_value"
                  :label="tsa.speed_description"
                  :value="tsa"/>
              </el-select>
            </div>
          </div>
          <div class="time-actions">
            <el-button
                v-if="!isSimulating"
                type="primary"
                size="small"
                @click="startSimulation"
            >
              开始模拟
            </el-button>
            <el-button
                v-else
                :type="isPaused ? 'success' : 'warning'"
                size="small"
                @click="togglePause"
            >
              {{ isPaused ? '继续模拟' : '暂停模拟' }}
            </el-button>
            <el-button
                type="danger"
                size="small"
                @click="stopSimulation"
                :disabled="!isSimulating"
            >
              停止模拟
            </el-button>
            <el-button
                type="info"
                size="small"
                @click="resetSimulation"
            >
              重置模拟
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- BI信息展示 -->
    <div class="section-title">
      <el-icon><DataAnalysis /></el-icon>
      <span>数据概览</span>
    </div>
    <el-row :gutter="20" class="bi-cards">
      <el-col :span="8">
        <el-card shadow="hover" class="bi-card">
          <template #header>
            <div class="bi-header">
              <el-icon><DataLine /></el-icon>
              <span>今日新闻量</span>
            </div>
          </template>
          <div class="bi-content">
            <h3>{{ biData.todayNewsCount.toLocaleString() }}</h3>
            <div class="trend">
              <span :class="biData.newsTrend >= 0 ? 'up' : 'down'">
                {{ biData.newsTrend >= 0 ? '↑' : '↓' }}{{ Math.abs(biData.newsTrend) }}%
              </span>
              <span>较昨日</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card shadow="hover" class="bi-card">
          <template #header>
            <div class="bi-header">
              <el-icon><View /></el-icon>
              <span>热门新闻点击量</span>
            </div>
          </template>
          <div class="bi-content">
            <h3>{{ biData.topNewsClicks.toLocaleString() }}</h3>
            <p class="top-news">
              <el-tag type="info" size="small" effect="light">{{ biData.topNewsTitle }}</el-tag>
            </p>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card shadow="hover" class="bi-card">
          <template #header>
            <div class="bi-header">
              <el-icon><User /></el-icon>
              <span>用户活跃度</span>
            </div>
          </template>
          <div class="bi-content">
            <h3>{{ biData.activeUsers.toLocaleString() }}</h3>
            <div class="trend">
              <span :class="biData.userTrend >= 0 ? 'up' : 'down'">
                {{ biData.userTrend >= 0 ? '↑' : '↓' }}{{ Math.abs(biData.userTrend) }}%
              </span>
              <span>较昨日</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 系统功能展示 -->
    <div class="section-title">
      <el-icon><Menu /></el-icon>
      <span>系统功能</span>
    </div>
    <el-row :gutter="20" class="function-cards">
      <el-col :span="6" v-for="func in systemFunctions" :key="func.title">
        <el-card shadow="hover" class="function-card">
          <template #header>
            <div class="function-header">
              <el-icon :size="20" :color="func.color"><component :is="func.icon" /></el-icon>
              <span>{{ func.title }}</span>
            </div>
          </template>
          <div class="function-content">
            <p class="func-desc">{{ func.description }}</p>
            <el-button type="text" @click="navigateTo(func.path)">进入功能 →</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'
import { useSimulationStore } from '@/store/simulation'
import {
  Clock,
  Menu,
  DataAnalysis,
  DataLine,
  View,
  User,
  Document,
  Search,
  Histogram,
  Connection,
  Collection
} from '@element-plus/icons-vue'
import {onMounted, onUnmounted, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";

const router = useRouter()
const simulationStore = useSimulationStore()

// 从store中解构需要的状态和方法
const {
  initialTime,
  currentTime,
  formattedTime,
  timeSpeed,
  isSimulating,
  isPaused,
} = storeToRefs(simulationStore)

const {
  formatDateTime
} = simulationStore
const timeSpeedArray = ref([
  {
    speed_description: "1s/s",
    speed_value: 1,
    real_time: 1000
  },
  {
    speed_description: "1min/2s",
    speed_value: 60,
    real_time: 2000
  },
  {
    speed_description: "0.5h/2s",
    speed_value: 1800,
    real_time: 2000
  },
  {
    speed_description: "1h/3s",
    speed_value: 3600,
    real_time: 3000
  },
  {
    speed_description: "0.5d/4s",
    speed_value: 43200,
    real_time: 4000
  },
  {
    speed_description: "1d/5s",
    speed_value: 86400,
    real_time: 5000
  },
  {
    speed_description: "1w/10s",
    speed_value: 604800,
    real_time: 10000
  }
])
const {
  startSimulation,
  stopSimulation,
  resetSimulation,
  togglePause  // 新增暂停/继续方法
} = simulationStore

// 系统功能列表
const systemFunctions = [
  {
    title: '曝光日志',
    description: '查看新闻曝光记录和分析',
    icon: Document,
    color: '#409EFF',
    path: '/impression'
  },
  {
    title: '变化查询',
    description: '查询新闻内容变化历史',
    icon: Search,
    color: '#67C23A',
    path: '/change'
  },
  {
    title: '统计查询',
    description: '新闻数据统计与分析',
    icon: Histogram,
    color: '#E6A23C',
    path: '/statistics'
  },
  {
    title: '分析与推荐',
    description: '新闻内容分析与推荐',
    icon: Connection,
    color: '#F56C6C',
    path: '/analysis'
  },
  {
    title: '查询日志',
    description: '用户查询行为记录',
    icon: Collection,
    color: '#909399',
    path: '/query'
  }
]

// BI数据
const biData = ref({
  todayNewsCount: 0,
  newsTrend: 0,
  topNewsClicks: 0,
  topNewsTitle: "",
  activeUsers: 0,
  userTrend: 0
})

// 定时器ID
let biDataTimer: number | null = null

const fetchBiData = async () => {
  try {
    const currentTime = new Date(formattedTime.value)
    const isMidnight = currentTime.getHours() === 0 &&
        currentTime.getMinutes() === 0 &&
        currentTime.getSeconds() === 0

    // 获取今日数据
    const todayStart = new Date(currentTime)
    todayStart.setHours(0, 0, 0, 0)

    // 获取昨日数据
    const yesterdayStart = new Date(todayStart)
    yesterdayStart.setDate(yesterdayStart.getDate() - 1)

    // 获取前日数据
    const dayBeforeYesterdayStart = new Date(yesterdayStart)
    dayBeforeYesterdayStart.setDate(dayBeforeYesterdayStart.getDate() - 1)

    let todayParams, yesterdayParams

    if (isMidnight) {
      // 当前时间是00:00:00的情况
      todayParams = {
        start_time: formatDateTime(yesterdayStart),
        end_time: formatDateTime(todayStart)
      }
      yesterdayParams = {
        start_time: formatDateTime(dayBeforeYesterdayStart),
        end_time: formatDateTime(yesterdayStart)
      }
    } else {
      // 当前时间不是00:00:00的情况
      todayParams = {
        start_time: formatDateTime(todayStart),
        end_time: formatDateTime(currentTime)
      }
      yesterdayParams = {
        start_time: formatDateTime(yesterdayStart),
        end_time: formatDateTime(todayStart)
      }
    }

    // 并发请求今日和昨日数据
    const [todayRes, yesterdayRes] = await Promise.all([
      axios.get('http://localhost:5000/get_news_stats', { params: todayParams }),
      axios.get('http://localhost:5000/get_news_stats', { params: yesterdayParams })
    ])

    const todayData = todayRes.data.data.summary
    const yesterdayData = yesterdayRes.data.data.summary

    // 计算趋势
    const newsTrend = yesterdayData.total_news > 0
        ? Math.round(((todayData.total_news - yesterdayData.total_news) / yesterdayData.total_news) * 100)
        : 0

    const userTrend = yesterdayData.user_count > 0
        ? Math.round(((todayData.user_count - yesterdayData.user_count) / yesterdayData.user_count) * 100)
        : 0

    // 获取点击量最高的新闻类别
    let topCategory = ''
    let maxExposures = 0
    todayRes.data.data.by_category.forEach((item:any) => {
      if (item.exposure_count > maxExposures) {
        maxExposures = item.exposure_count
        topCategory = item.category
      }
    })

    // 更新BI数据
    biData.value = {
      todayNewsCount: todayData.total_news,
      newsTrend,
      topNewsClicks: maxExposures,
      topNewsTitle: topCategory,
      activeUsers: todayData.user_count,
      userTrend
    }

  } catch (error) {
    console.error('获取BI数据失败:', error)
    ElMessage.error('获取数据失败')
  }
}

// 启动定时获取BI数据
const startBiDataTimer = () => {
  // 先立即获取一次数据
  fetchBiData()

  // 然后设置定时器每5秒获取一次
  biDataTimer = setInterval(fetchBiData, 5000)
}

// 停止定时获取BI数据
const stopBiDataTimer = () => {
  if (biDataTimer) {
    clearInterval(biDataTimer)
    biDataTimer = null
  }
}
// 导航功能
const navigateTo = (path: string) => {
  router.push(path)
}

// 组件挂载时启动定时器
onMounted(() => {
  startBiDataTimer()
})
// 组件卸载时停止定时器
onUnmounted(() => {
  stopBiDataTimer()
})
</script>

<style scoped>
.home-container {
  padding: 20px;
}

h2 {
  margin-bottom: 24px;
  color: #303133;
  font-size: 24px;
}

.time-control {
  margin-bottom: 28px;
}

.time-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.time-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.time-display {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 15px;
}

.time-config {
  display: flex;
  gap: 20px;
  margin: 12px 0;
}

.time-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.time-item .label {
  font-size: 14px;
  color: #606266;
}

.time-actions {
  display: flex;
  gap: 12px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 28px 0 16px 0;
  font-size: 18px;
  color: #303133;
  font-weight: 500;
}

.function-cards {
  margin-bottom: 28px;
}

.function-card {
  height: 180px;
  margin-bottom: 20px;
}

.function-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
}

.function-content {
  height: calc(100% - 60px);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.func-desc {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 12px;
}

.bi-cards {
  margin-bottom: 20px;
}

.bi-card {
  height: 100%;
}

.bi-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
}

.bi-content {
  padding: 8px 0;
}

.bi-content h3 {
  font-size: 26px;
  margin: 12px 0;
  color: #303133;
}

.trend {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: #909399;
}

.up {
  color: #67C23A;
  font-weight: 500;
}

.down {
  color: #F56C6C;
  font-weight: 500;
}

.top-news {
  margin-top: 12px;
}
</style>